#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
#include <stdlib.h>

#include "interaction.h"
#include "app.h"
#include "log.h"
#include "ticket_device.h"
#include "login_device.h"

/**
 * @brief   初始化
 * @param   app:包含所有信息的指针
 *          p_func:函数指针数组
 * @return  NULL:传参失败、申请内存失败、初始化错误
 *          p_func:正常运行
 */
func_t *init(struct app *app, func_t *p_func)
{
    if (!app) {
        DEBUG("PARAM ERROR!");
        return NULL;
    }

    int ret;

    app->interaction = (struct interaction *)malloc
                        (sizeof(struct interaction));
    if (!app->interaction) {
        DEBUG("MALLOC ERROR!");
        return NULL;
    }

    p_func[USER_LOGIN] = user_login;
    p_func[USER_REGISTER] = user_register;
    p_func[ADD_TICKET] = add_ticket;
    p_func[BUY_TICKET] = buy_ticket;
    p_func[RETURN_TICKET] = return_ticket;
    p_func[MAIN_MENU] = main_menu;
    p_func[USER_MENU] = user_menu;
    p_func[ADMIN_MENU] = admin_menu;
    p_func[ADMIN_LOGIN] = admin_login;
    p_func[MODIFY_USER] = modify_user;
    p_func[MODIFY_TICKET] = modify_ticket;

    app->interaction->admin = (struct admin *)malloc(sizeof(struct admin));
    if (!app->interaction->admin) {
        DEBUG("MALLOC ERROR!");
        return NULL;
    }
    
    admin_init(app->interaction->admin);

    ret = ticket_init(&app->interaction->ticket_head,
                        &app->interaction->user_ticket_head);
    if (ret != true) {
        return NULL;
    }

    ret = user_init(&app->interaction->user_head);
    if (ret != true) {
        DEBUG("USER INIT ERROR!");
        return NULL;
    }

    /*界面信息初始化*/
    ui_init(app->interaction->ui_data);

    return p_func;
}

/**
 * @brief   run
 * @param   app:包含所有信息的指针
 *          p_func:函数指针数组
 * @return  MALLOC_ERROR:申请内存失败
 *          true:正常运行
 */
int run(struct app *app, func_t *p_func)
{
    if (!app || !p_func) {
        DEBUG("PARAM ERROR!");
        return PARAM_ERROR;
    }

    int ret;

    ret = control_func(app->interaction, p_func);
    if (ret != true) {
        DEBUG("CONTROL_FUNC ERROR!");
        return false;
    }

    return true;
}

/**
 * @brief   destroy
 * @param   app:包含所有信息的指针
 * @return  MALLOC_ERROR:申请内存失败
 *          true:正常运行
 */
int destroy(struct app *app)
{
    int ret;

    system("clear");
    ret = user_destroy(&app->interaction->user_head);
    if (ret != true) {
        DEBUG("USER DESTROY ERROR!");
        return false;
    }

    ret = ticket_destroy(&app->interaction->ticket_head,
                            &app->interaction->user_ticket_head);
    if (ret != true) {
        DEBUG("TICKET DESTROY ERROR!");
        return false;
    }

    admin_destroy(app->interaction->admin);

    free(app->interaction);
    free(app);

    return true;
}